import React, { Component, Fragment } from 'react';
import { Table, Col, Button, Icon, Checkbox, message, Row } from 'antd';
import _ from 'lodash';
import { connect } from 'dva';
import styles from './index.less';
import Eject from '@/components/Eject';
import * as apis from '@/services/SystemMgr';
import * as utils from '../../../utils/method';

@connect(state => ({
  Permissions: state.Permissions,
}))
export default class SetFunctionJurisdiction extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      treeData: [],
      columns: [
        {
          title: '菜单',
          dataIndex: 'perName',
          render: (text, record) => (
            <Fragment>
              &nbsp;&nbsp;
              <Checkbox
                checked={record.flag * 1 === 1}
                onChange={e => this.handleCheckedChange(record, e)}
              />
              &nbsp;&nbsp;
              {text}
            </Fragment>
          ),
        },
        {
          title: '操作',
          dataIndex: 'btns',
          width: '55%',
          render: (text, record) => (
            <Row type="flex">
              {text.map((item, index) => (
                <Col span={8} key={item.key}>
                  <Checkbox
                    checked={item.flag * 1 === 1}
                    onChange={e => this.handleRadioChange(record, index, e)}
                  >
                    {item.perName}
                  </Checkbox>
                </Col>
              ))}
            </Row>
          ),
        },
      ],
    };
  }

  // 获取平拉数据
  getCheckedId = (items, newData) => {
    items.forEach(checkedNode => {
      newData.push(checkedNode);
      checkedNode.btns.forEach(item => {
        newData.push(item);
      });
      if (checkedNode.children && checkedNode.children.length > 0) {
        this.getCheckedId(checkedNode.children, newData);
      }
    });
    return newData;
  };

  // 获取数据
  async getFunctionTree(id) {
    let key;
    let url;
    if (this.props.info === '岗位组信息') {
      key = 'positionGroupId';
      url = 'getSysPositionGroupPermissionTreeUsingGET';
    }
    if (this.props.info === '角色组信息') {
      key = 'roleId';
      url = 'getSysRolePermissionTreeUsingGET';
    }
    const params = {
      apiVersion: 'v1',
      [key]: id,
    };
    const getData = await apis[url]({ params });
    if (getData.code === 1) {
      getData.data.list.forEach(element => {
        const x = element;
        x.key = element.perId;
        x.btns = [];
      });
      const items = _.cloneDeep(utils.translateDataToTree(getData.data.list, ''));
      this.setState({
        treeData: items,
      });
    }
  }

  clearChecked = items => {
    _.forEach(items, item => {
      const x = item;
      x.flag = 0;
      x.btns.forEach(v => {
        const j = v;
        j.flag = 0;
      });
      if (item.children && item.children.length > 0) {
        this.clearChecked(item.children);
      }
    });
    return items;
  };

  // 循环选中子节点
  checkboxChangeMyNodes = (root, checked) => {
    const node = root;
    node.flag = checked;

    if (root.btns && root.btns.length > 0) {
      root.btns.forEach(item => {
        const x = item;
        x.flag = checked;
      });
    }

    if (root.children && root.children.length > 0) {
      root.children.forEach(element => {
        const x = element;
        x.flag = checked;
        this.checkboxChangeMyNodes(x, checked);
      });
    }
  };

  // 找出选中所有父级
  filterParent = (data2, nodeId2) => {
    const rev = (data, nodeId) => {
      for (let i = 0, { length } = data; i < length; i += 1) {
        const node = data[i];
        if (node.perCode === nodeId) {
          this.changeSubIsChecked(data2, node.perCode);
          rev(data2, node.parentCode);
          break;
        } else if (node.children) {
          rev(node.children, nodeId);
        }
      }
    };
    rev(data2, nodeId2);
  };

  changeSubIsChecked = (tree, pid) => {
    // console.log(tree, pid)
    tree.forEach(subNode => {
      if (subNode.perCode === pid) {
        const filterItems = _.filter(subNode.children, item => item.flag * 1 === 1);
        if (filterItems.length > 0) {
          subNode.flag = 1;
        } else {
          subNode.flag = 0;
        }
      }
      if (subNode.children && subNode.children.length > 0) {
        this.changeSubIsChecked(subNode.children, pid);
      }
    });
  };

  // 菜单---checked
  handleCheckedChange = (record, e) => {
    const serl = this;
    const items = _.cloneDeep(serl.state.treeData);
    const root = utils.findNode(items, record.key);
    this.checkboxChangeMyNodes(root, e.target.checked ? 1 : 0);
    this.filterParent(items, record.parentCode);
    this.setState({
      treeData: items,
    });
  };

  // 操作选择
  handleRadioChange = (record, index, e) => {
    const sfl = this;
    const items = _.cloneDeep(sfl.state.treeData);
    const root = utils.findNode(items, record.key);
    root.btns[index].flag = e.target.checked ? 1 : 0;
    const filterRoot = _.filter(root.btns, x => x.flag * 1 === 1);
    if (filterRoot.length > 0) {
      root.flag = 1;
    } else {
      root.flag = 0;
    }
    this.filterParent(items, root.parentCode);
    this.setState({
      treeData: items,
    });
  };

  // 点击弹出
  handleShowDrawer = () => {
    this.setState({
      visible: true,
    });
    this.getFunctionTree(this.props.Id);
  };

  // 点击收起
  handleOnClose = () => {
    this.setState({
      visible: false,
    });
  };

  // 确定
  handleOkBtnClick = async () => {
    const items = _.cloneDeep(this.state.treeData);
    let url;
    const params = {};
    if (this.props.info === '岗位组信息') {
      url = 'createSysPositionGroupPermissionUsingPOST';
      params.positionGroupId = this.props.Id;
    } else if (this.props.info === '角色组信息') {
      url = 'createSysRolePermissionUsingPOST';
      params.roleId = this.props.Id;
    }
    const newData = this.getCheckedId(items, []);
    const keys = _.filter(newData, item => item.flag * 1 === 1);
    params.perIds = [];
    keys.forEach(item => {
      params.perIds.push(item.key);
    });
    const data = await apis[url]({ data: params });
    if (data.code === 1) {
      message.success(data.message);
      this.setState({
        visible: false,
      });
    }
  };

  // 清空选中
  handleClearBtnClick = () => {
    const serl = this;
    const items = _.cloneDeep(serl.state.treeData);
    this.clearChecked(items);
    this.setState({ treeData: items });
  };

  render() {
    const { columns, treeData, visible } = this.state;
    const { info, infoName, recordName, describe } = this.props;
    return (
      <Eject
        btnType="link"
        value="设置功能权限"
        title="设置功能权限"
        width={800}
        showDrawer={this.handleShowDrawer}
        handleOkBtnClick={this.handleOkBtnClick}
        onClose={this.handleOnClose}
        visible={visible}
        modelJsx={
          <div className={styles['set-function-jurisdiction']}>
            <h3>{info}</h3>
            <div className={styles.title}>
              <span>{infoName}</span>
              {recordName} <br />
              <span style={{ display: info === '角色组信息' ? '' : 'none' }}>角色描述:</span>
              {describe}
            </div>
            <div className={styles['table-title']}>
              权限管理
              <Button onClick={this.handleClearBtnClick}>清空</Button>
            </div>
            <Table
              columns={columns}
              dataSource={treeData}
              pagination={false}
              scroll={{ y: 'calc(100vh - 300px)' }}
              size="middle"
              bordered
              loading={!(treeData && treeData.length > 0)}
              expandIcon={props => {
                let text;
                if (props.expanded) {
                  text = 'caret-down';
                } else if (props.record.children && props.record.children.length > 0) {
                  text = 'caret-right';
                } else {
                  text = 'null';
                }
                return (
                  <Icon
                    type={text}
                    className="expand-row-icon"
                    onClick={e => props.onExpand(props.record, e)}
                    style={{ cursor: 'pointer' }}
                  />
                );
              }}
            />
          </div>
        }
      />
    );
  }
}
